﻿using Newtonsoft.Json;

namespace CTP.CRM.Core.JsonSerialization
{
    //
    // 摘要:
    //     处理DateTime、DateTime?格式
    public class DateTimeJsonConverter : JsonConverter
    {
        private readonly string _format;

        public DateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss")
        {
            _format = format;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime) || objectType == typeof(DateTime?);
        }

        public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null || string.IsNullOrEmpty(reader.Value.ToString()))
            {
                return null;
            }

            if (DateTime.TryParse(reader.Value.ToString(), out var result))
            {
                return result;
            }

            return default(DateTime);
        }

        public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString(_format));
        }
    }
}
